package com.example.springpethospital.entity.examination.po;

import com.example.springpethospital.common.exception.PetHospitalException;
import java.util.LinkedList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExaminationPaperPO {

    private Integer id;

    private String paperTitle;

    private Integer totalTime;

    private Integer totalScore;

    private List<ExaminationPaperQuestion> questions;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ExaminationPaperQuestion {

        private Integer questionId;

        private Integer score;
    }

    public void check(boolean update) {
        List<String> errorMessage = new LinkedList<>();
        if (update && id == null) {
            errorMessage.add("主键id不可为空");
        }
        if (StringUtils.isEmpty(paperTitle)) {
            errorMessage.add("试卷标题不可为空");
        }
        if (totalTime <= 0) {
            errorMessage.add("考试时间必须大于0");
        }
        if (totalScore <= 0) {
            errorMessage.add("试卷总分必须大于0");
        }
        if (CollectionUtils.isEmpty(questions)) {
            errorMessage.add("试卷题目不可为空");
        }
        if (questions.stream().anyMatch(e -> e.getQuestionId() == null || e.getScore() == null || e.getQuestionId() <= 0 || e.getScore() <= 0)) {
            errorMessage.add("试卷题目参数中存在不合法数据, 请修改后重试");
        }
        if (!questions.stream().map(ExaminationPaperQuestion::getScore).reduce(Integer::sum).orElse(0).equals(totalScore)) {
            errorMessage.add("试卷题目分数和不等于试卷总分");
        }
        if (CollectionUtils.isNotEmpty(errorMessage)) {
            throw new PetHospitalException(String.join("|", errorMessage));
        }
    }

}
